import { createStore, applyMiddleware, compose } from 'redux'
// 引入中间件
import thunk from 'redux-thunk'

// 它就可以帮你解决深拷贝
import _ from 'lodash/lang'

// 默认数据
const defaultState = {
  // 半依赖  列表中依赖，在添加和修改操作没有依赖，而是操作了数据库
  users: [],
  userinfo: {}
}
// 纯函数
// state不可修改
// action是一个操作对象
/*
{
  type:操作名称
  payload:数据
}
*/
// 返回是一个新的state  注意 对象深拷贝
function userReducer(state = defaultState, action) {
  if ('getusers' === action.type) {
    // 深拷贝
    // let newState = JSON.parse(JSON.stringify(state))
    /* let newState = { ...state }
    newState.users = newState.users.concat(action.payload)
    return newState */
    // {...state} // {users:[ { _id: 100, username: '张三' },{},{}]}
    return { users: [...state.users, ...action.payload] }

  } else if ('getuserinfo' === action.type) {  // 获取数据
    return {
      ...state,
      userinfo: action.payload
    }
  } else if ('setUserinfo' === action.type) {
    return {
      // 清空
      users: []
    }
  } else if ('deleteUser' === action.type) {
    let newState = _.cloneDeep(state)
    newState.users.splice(action.payload, 1)
    return newState
  }

  return state

}


// 配置chrome中的redux扩展可视化操作
const composeEnhancers =
  typeof window === 'object' &&
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose
const enhancer = composeEnhancers(
  applyMiddleware(thunk)
)

export default createStore(
  userReducer,
  enhancer
)


























